package com.itqf.service.impl;

import com.itqf.entity.Account;
import com.itqf.entity.TransactionRecord;
import com.itqf.mapper.AccountMapper;
import com.itqf.service.AccountService;
import com.itqf.service.TransactionRecordService;

import java.util.Date;

/**
 * @Description:
 * @Company: 千锋互联
 * @Author: 李丽婷
 * @Date: 2020/11/12
 * @Time: 上午10:32
 */
public class AccountServiceImpl implements AccountService {

    //依赖dao
    private AccountMapper accountMapper;

    public void setAccountMapper(AccountMapper accountMapper) {
        this.accountMapper = accountMapper;
    }

    private TransactionRecordService transactionRecordService;

    public void setTransactionRecordService(TransactionRecordService transactionRecordService) {
        this.transactionRecordService = transactionRecordService;
    }

    @Override
    public void transfer(String fromCardno, String toCardno, int money) {
            //1.构建账号对象
        Account fromAccount = accountMapper.findById(fromCardno);
        if (fromAccount.getAccountBalance()<money){
            throw  new RuntimeException("余额不足！！");
        }else{
            //原来的钱-转出的钱
            fromAccount.setAccountBalance(fromAccount.getAccountBalance()-money);
            accountMapper.update(fromAccount);

            //int   i = 10/0;//模拟异常
            Account toAccount = null;

            try {
                //2.构建转入账号对象
                toAccount = accountMapper.findById(toCardno);
                // 原来的钱+转入的钱
                toAccount.setAccountBalance(toAccount.getAccountBalance()+money);

                //3.把转账信息保存到记录表
                TransactionRecord fromRecord = new TransactionRecord();
                fromRecord.setCardno(fromCardno);
                fromRecord.setAccountBalance(fromAccount.getAccountBalance());
                fromRecord.setExpense(money);
                fromRecord.setTransactionDate(new Date());
                fromRecord.setTransactionType("转出");
                fromRecord.setRemark("房租");
                transactionRecordService.insertRecord(fromRecord);

                TransactionRecord toRecord = new TransactionRecord();
                toRecord.setCardno(toCardno);
                toRecord.setAccountBalance(toAccount.getAccountBalance());
                toRecord.setIncome(money);
                toRecord.setTransactionDate(new Date());
                toRecord.setTransactionType("转入");
                toRecord.setRemark("房租");
                transactionRecordService.insertRecord(toRecord);
            } catch (Exception e) {
                e.printStackTrace();
            }


            accountMapper.update(toAccount);


        }
    }
}
